package com.neusoft.actor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.actor.dao.*;
import com.neusoft.actor.dto.OutgoingRequestWithClientDto;
import com.neusoft.actor.po.*;
import com.neusoft.actor.service.OutgoingRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OutgoingRequestServiceImpl implements OutgoingRequestService {

    @Autowired
    private OutgoingRequestDao outgoingRequestDao;

    @Autowired
    private BedDao bedDao;

    @Autowired
    private BedUsageDao bedUsageDao;

    @Autowired
    private CaretakerClientDao caretakerClientDao;

    @Autowired
    private ClientDao clientDao;

    @Override
    public ResponseBean<List<OutgoingRequest>> getAllOutgoingRequests() {
        List<OutgoingRequest> outgoingRequests = outgoingRequestDao.selectList(null);
        return new ResponseBean<>(outgoingRequests);
    }



    @Override
    public ResponseBean<OutgoingRequest> getOutgoingRequestById(Integer requestId) {
        OutgoingRequest outgoingRequest = outgoingRequestDao.selectById(requestId);
        if (outgoingRequest != null) {
            return new ResponseBean<>(outgoingRequest);
        } else {
            return new ResponseBean<>(404, "外出申请未找到");
        }
    }
    @Override
//    同意外出请求
    public ResponseBean<Integer> passOutgoingRequest(OutgoingRequest outgoingRequest) {
        Bed bed;
        Integer clientId = outgoingRequest.getClientId();
        BedUsage bedUsage = bedUsageDao.selectOne(
                new QueryWrapper<BedUsage>().eq("usage_id", clientId).eq("is_current", 1)
        );
        if (bedUsage != null) {
            Integer bedId = bedUsage.getBedId();
            bed = bedDao.selectById(bedId);
            if (bed != null) {
                bed.setStatus("外出");
                bedDao.updateById(bed);
            }
        }
        int result = outgoingRequestDao.updateById(outgoingRequest);
        return new ResponseBean<>(result);
    }

    @Override
//    条件查询外出请求的客户信息 + 连接多表
    public ResponseBean<List<OutgoingRequestWithClientDto>> getOutgoingRequests(String clientName, String isSelfCare) {
        List<OutgoingRequestWithClientDto> result = outgoingRequestDao.getOutgoingRequestsByConditions(clientName, isSelfCare);
        if (result != null) {
            return new ResponseBean<>(result);
        } else {
            return new ResponseBean<>(404,"未找到");
        }
    }

    @Override
//    查询健康管家管理客户的申请表，可根据姓名模糊查询
    public ResponseBean<List<OutgoingRequestWithClientDto>> getOutgoingRequestsByCareTakerId(Integer careTakerId, String clientName) {
        // 查询健康管家管理的所有客户ID，同样可以调用方法
        List<CaretakerClient> caretakerClients = caretakerClientDao.selectList(new QueryWrapper<CaretakerClient>().eq("caretaker_id", careTakerId));
        List<Integer> clientIds = caretakerClients.stream()
                .map(CaretakerClient::getClientId)
                .collect(Collectors.toList());

        // 如果没有客户，直接返回404
        if (clientIds.isEmpty()) {
            return new ResponseBean<>(404, "该健康管家没有客户");
        }

        // 查询所有客户的外出申请
        List<OutgoingRequestWithClientDto> allOutgoingRequests = new ArrayList<>();
        for (Integer clientId : clientIds) {
            List<OutgoingRequest> outgoingRequests1 = outgoingRequestDao.selectList(new QueryWrapper<OutgoingRequest>().eq("client_id", clientId));
            for (OutgoingRequest request : outgoingRequests1) {
                Client client = clientDao.selectById(request.getClientId());
                if (client != null) {
                    OutgoingRequestWithClientDto dto = new OutgoingRequestWithClientDto();
                    dto.setRequestId(request.getRequestId());
                    dto.setClientName(client.getClientName());
                    dto.setClientId(request.getClientId());
                    dto.setSelfCare(client.getIsSelfCare());
                    dto.setRoomNumber(client.getRoomNumber());
                    dto.setAge(client.getAge());
                    dto.setReason(request.getReason());
                    dto.setDepartureTime(request.getDepartureTime());
                    dto.setReturnTime(request.getReturnTime());
                    dto.setActualReturnTime(request.getActualReturnTime());
                    dto.setStatus(request.getStatus());
                    dto.setRemark(request.getRemark());
                    allOutgoingRequests.add(dto);
                }
            }
        }

        // 如果提供了客户名称，则进行模糊查询
        if (clientName != null && !clientName.isEmpty()) {
            allOutgoingRequests = allOutgoingRequests.stream()
                    .filter(request -> request.getClientName().contains(clientName))
                    .collect(Collectors.toList());
        }

        // 返回结果
        if (!allOutgoingRequests.isEmpty()) {
            return new ResponseBean<>(allOutgoingRequests);
        } else {
            return new ResponseBean<>(404, "未找到符合条件的外出申请");
        }
    }

    @Override
    public ResponseBean<Integer> addOutgoingRequest(OutgoingRequest outgoingRequest) {
        int result = outgoingRequestDao.insert(outgoingRequest);
        return new ResponseBean<>(result); // 返回插入成功的行数
    }

    @Override
    public ResponseBean<Integer> updateOutgoingRequest(OutgoingRequest outgoingRequest) {
        int result = outgoingRequestDao.updateById(outgoingRequest);
        return new ResponseBean<>(result); // 返回更新成功的行数
    }

    @Override
    public ResponseBean<Integer> deleteOutgoingRequest(Integer requestId) {
        int result = outgoingRequestDao.deleteById(requestId);
        return new ResponseBean<>(result); // 返回删除成功的行数
    }
}